<?php
include_once("../configure/configure.php");		//--> global var
include_once("../admin/configure/admin.config.inc.php");		//--> global var
include_once("constant/GlobalConstant.php");

include_once("utils/StringUtils.php");
include_once("utils/ConvertUtils.php");

include_once("impl/MerchantImpl.php");

$merImpl 	= new MerchantImpl(DB_TAG_COUPON);

set_time_limit(0);

$pageNum = $_GET['pageNum'];
if(empty($pageNum))
	$pageNum = 1;

// new c2b1a8b0e8016cefd05882f30af7c7abfcc8dae694daabad758b63307da5e284
$token = 'c2b1a8b0e8016cefd05882f30af7c7abfcc8dae694daabad758b63307da5e284';
$URI = "http://couponfeed.linksynergy.com/coupon?token=$token&resultsperpage=500&network=1|3|5|41&pagenumber=$pageNum";

echo "\nURI: " . $URI . "\n";

$couponFeed = new SimpleXMLElement(file_get_contents($URI));

$totalPagesNode = $couponFeed->xpath('/couponfeed/TotalPages');

$totalPages = 0;
foreach ($totalPagesNode as $pageNode) {
	$totalPages = $pageNode;
}

echo "totalPages: " . $totalPages . "\n";
$totalCount			= 0;
$newCouponCount 	= 0;
$existedCouponCount	= 0;
$noFoundMerCount	= 0;
$newCategoryCount	= 0;

do{
	$linkNodes = $couponFeed->xpath('/couponfeed/link');
	
	
	foreach ($linkNodes as $node) {
		$totalCount++;
		
		$cats 	= array();
		$types 	= array();
	//	echo "\n----------------- coupon info -------------------------";
		
		foreach($node->categories->children() as $value){
			$cats[] = $value;
		}
	
		foreach($node->promotiontypes->children() as $value){
			$types[] = $value;
		}
		
	//	echo "\n offerdescription: " . $node->offerdescription;
	//	echo "\n offerstartdate: " . $node->offerstartdate;
	//	echo "\n offerenddate: " . $node->offerenddate;
	//	
	//	echo "\n couponcode: " . $node->couponcode;
	//	echo "\n couponrestriction: " . $node->couponrestriction ;
	//	
	//	echo "\n clickurl: " . $node->clickurl;
	//	
	//	echo "\n impressionpixel: " . $node->impressionpixel;
	//	echo "\n advertiserid: " . $node->advertiserid;
	//	echo "\n advertisername: " . $node->advertisername;
	//
	//	echo "\n network : " . $node->network;
		
	//	foreach($cats as $cat){
	//		echo "\n";
	//		echo "			cat value : " . $cat;
	//	}
	//	
	//	foreach($types as $promotiontype){
	//		echo "\n";
	//		echo "			promotiontype : " . $promotiontype;
	//	}
			
			
		$name 				= $node->offerdescription;
		$advertiserId 		= $node->advertiserid;
		$trackingURL		= $node->clickurl;
		$creativeURL		= 'null';
		$imageSize 			= 'null';
		$trackingHtmlCode	= 'null';
		
		$startDate			= $node->offerstartdate;
		$endDate			= $node->offerenddate;
		
		$creativeType		= '2';
		
		$descript			= $node->couponrestriction;
		$code				= $node->couponcode;
		$impressionpixel	= $node->impressionpixel;
		
		$categoryId			= 0;
		
		similar_text($name, $descript, $similar);
		
		if(empty($descript) || $name == $descript || number_format($similar, 0) > 90)
			$descript = 'null';
		
		$merchantID = $merImpl->getColumn(DB_TAG_COUPON, "SELECT ma.merchantId FROM merchant_attributes ma" .
				" WHERE ma.attributeId = 22 AND ma.attributeValue = '$advertiserId'");
				
		if(!empty($merchantID)){
			$categoryIds = array();
			
	//		echo "\n			merchantID : " . $merchantID;
			foreach($cats as $cat){
	//			echo "\n			cat value : " . $cat;
			
				$categoryId = $merImpl->getColumn(DB_TAG_COUPON, "SELECT id FROM category WHERE name = '$cat' AND isLeaf = 1");
				
				if(empty($categoryId)){
					$categoryId = $merImpl->getColumn(DB_TAG_COUPON, "SELECT categoryId FROM category_alias WHERE alias = '$cat'");
				}
				
				if(empty($categoryId)){
					$sql_data_array = array(
						'name' 		=> $cat,
						'descript' 	=> '',
						'title' 	=> '',
						'status' 	=> '1',
						'parentId' 	=> '-1'
					);
						
					$categoryId = $merImpl->insertArray(DB_TAG_COUPON, 'category', $sql_data_array);
					
					$sql_data_array = array(
						'aliasName' 	=> $cat,
						'categoryId' 	=> $categoryId
					);
						
					$merImpl->insertArray(DB_TAG_COUPON, 'category_alias', $sql_data_array);
					
					$newCategoryCount++;
				}
			
	//			echo "\n			categoryId : " . $categoryId;
				if(!empty($categoryId)){
					$categoryIds[] = $categoryId;
					
					$mcID = $merImpl->getColumn(DB_TAG_COUPON, "SELECT categoryId FROM merchant_category WHERE merchantId = $merchantID AND categoryId = $categoryId");
					if(empty($mcID)){
						$sql_data_array = array(
							'merchantId' 		=> $merchantID,
							'categoryId' 		=> $categoryId
						);
							
						$merImpl->insertArray(DB_TAG_COUPON, 'merchant_category', $sql_data_array, " ON DUPLICATE KEY UPDATE merchantId=Values(merchantId)");
					
						echo " \nmerchantId_categoryId = $merchantID_$categoryId \n";
						
					}
				}else{
					echo "\n			found not category, category name: $cat \n";
					echo "\n			coupon name: " . $name;
				}
			}
			
			
			
			if(empty($startDate)){
				$startDate = 'null';
			}else{
				$startDate = date('Y-m-d', strtotime($startDate));
			}
			
			if(empty($endDate)){
				$endDate = 'null';
			}else{
				$endDate = date('Y-m-d', strtotime($endDate));
			}
			
	//		$filtername 	= StringUtils::getStartValue(' from ', $name);
	//		$filtername 	= StringUtils::getStartValue(' at ', $name);
			$filtername		= $name;
			
	//		echo "\n		filter name: " . $filtername;
			
			$IDkey			= md5($merchantID . $code . $filtername . $descript);
			
			
			$couponID = $merImpl->getColumn(DB_TAG_COUPON, "SELECT id FROM coupon WHERE IDKey = '$IDkey'");
			
			if(empty($couponID) && !empty($filtername)){
				$sql_data_array = array(
					'name' 				=> $filtername,
					'merchantId'		=> $merchantID,
					'descript' 			=> $descript,
					'trackingURL' 		=> $trackingURL,
					'trackingHtmlCode' 	=> $trackingHtmlCode,
					
					'startDate' 		=> $startDate,
					'endDate' 			=> $endDate,
					
					'creativeType' 		=> $creativeType,
					
					'code' 				=> $code,
					'impressionpixel' 	=> $impressionpixel,
					
					'sourceId'			=> '3',
					'status' 			=> "1",
					'createdTime' 		=> "UTC_TIMESTAMP()",
					'IDkey' 			=> $IDkey
				);
				
				$couponID = $merImpl->insertArray(DB_TAG_COUPON, 'coupon', $sql_data_array, " ON DUPLICATE KEY UPDATE modifiedTime=Values(modifiedTime)");
	//			echo "\ninsert coupon id = $couponID \n";
				
				if(!empty($couponID)){
					foreach($categoryIds as $categoryId){
						$sql_data_array = array(
							'couponId'			=> $couponID,
							'categoryId' 		=> $categoryId,
						);
						
						$merImpl->insertArray(DB_TAG_COUPON, 'coupon_category', $sql_data_array, " ON DUPLICATE KEY UPDATE categoryId=Values(categoryId)");
					}
					
					foreach($types as $promotiontype){
	//					echo "\n";
	//					echo "			promotiontype : " . $promotiontype;
						
						$attributeIdForPromoType = ConvertUtils::getAttributeIdForPromoType($promotiontype);
						
						if(!empty($attributeIdForPromoType)){
							$sql_data_array = array(
								'couponId'			=> $couponID,
								'attributeId' 		=> $attributeIdForPromoType,
								'attributeValue' 	=> 'Promo Type'
							);
							
							$merImpl->insertArray(DB_TAG_COUPON, 'coupon_attributes', $sql_data_array, " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
						}else{
							echo "		not found promotion type : $promotiontype \n";
						}
					}
				}
				
				$newCouponCount++;
				
			}else{
				$existedCouponCount++;
					//echo $couponID ." id coupon is existed.\n";
			}
		}else{
			$noFoundMerCount++;
			echo "$advertiserId advertiserId is not existed.\n";
		}
		
	
	
	}
	
	$pageNum++;
	$URI 		= "http://couponfeed.linksynergy.com/coupon?token=$token&resultsperpage=500&network=1|3|5|41&pagenumber=$pageNum";
	
	if($pageNum <= $totalPages)
		echo "URI: " . $URI . "\n";

	$couponFeed = new SimpleXMLElement(file_get_contents($URI));	
}while($pageNum <= $totalPages);


echo "\n totalCount 			= $totalCount";

echo "\n newCouponCount 		= $newCouponCount";
echo "\n existedCouponCount 	= $existedCouponCount";
echo "\n noFoundMerCount 		= $noFoundMerCount";
echo "\n newCategoryCount 		= $newCategoryCount";


?>